package com.hhit.collaborative_learning.download;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.hhit.collaborative_learning.dao.impl.PublicDaoImplMySql;
@MultipartConfig
public class UploadFileServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Part file=request.getPart("txt_userfile");
		String txt_title=request.getParameter("txt_title");
		String filename=request.getParameter("filename");
		String category=request.getParameter("sel_filetype");
		String txt_tag=request.getParameter("txt_tag");
		txt_tag=txt_tag.replaceAll("\\s+",",");
		String type=request.getParameter("sel_primary");
		String point=request.getParameter("sel_score");
		String txt_desc=request.getParameter("txt_desc");
		String userId=request.getParameter("userId");
		String storeName="";
		String dataSize="";
		PrintWriter out=response.getWriter();
		PublicDaoImplMySql dao=new PublicDaoImplMySql();
		if(file!=null){
			long size=file.getSize();
			if(size>=60*1024*1024){
				out.print("文件大小超过60M，请重新选择！");
				return;
			}
			DecimalFormat df = new DecimalFormat("0.00");
			if(size<1024){
				dataSize+=size+"B";
			}else if(size>=1024&&size<1024*1024){
				dataSize+=df.format(size/(1024.0))+"KB";
			}else{
				dataSize+=df.format(size/(1024.0*1024.0))+"MB";
			}
			File path=new File(getServletContext().getRealPath("/uploadFile"));
			if(!path.exists()){
				path.mkdir();
			}
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String now = sdf.format(date);
			storeName=now+"_"+filename.replaceAll(" ", "_");
			File lastFile=new File(path, storeName);
			file.write(lastFile.getAbsolutePath());
			
			out.print(dao.uploadFile(Integer.parseInt(userId), Integer.parseInt(point), txt_title, type, category, txt_desc, txt_tag, dataSize, filename, storeName));
		}
	}

}
